package com.teatrace.service.impl;

import java.util.List;
import java.util.Set;

import javax.jws.WebService;

import org.hibernate.Query;

import com.antifake.CodeGenerator;
import com.antifake.CodeGeneratorFactory;
import com.dao.genericdao.IBaseDao;
import com.teatrace.service.cfg.Configure;
import com.teatrace.service.cfg.R;
import com.teatrace.model.AntiFakeCode;
import com.teatrace.service.AntiFakeService;
import com.teatrace.service.ServiceException;

@WebService(endpointInterface="com.teatrace.service.AntiFakeService")
public class AntiFakeServiceImpl implements AntiFakeService {
	
	private IBaseDao<AntiFakeCode, Integer> antiFakeDao; 

	@Override
	public void generateAndSaveIntoDB(int count, String pattern) {
		CodeGenerator generator = CodeGeneratorFactory.createByType(String.class);
		generator.setCount(count);
		generator.setDigit(Configure.getInt(R.CFG.AntiFakeCodeDigit));
		if(pattern != null) {
			if(pattern.contains(CodeGenerator.PLACE_HOLDER)) {
				generator.setPattern(pattern);
			} else {
				throw new ServiceException(R.ServiceErrorKey.AntiFake_InvalidPattern);
			}
		}
		Set<String> codeSet = generator.generate();
		for(String code : codeSet) {
			AntiFakeCode antiFakeCode = new AntiFakeCode();
			antiFakeCode.setApply(false);
			antiFakeCode.setValidateCount(0);
			antiFakeCode.setCode(code);
			antiFakeDao.save(antiFakeCode);
		}
	}
	
	@Override
	public AntiFakeCode get(String code) {
		List<AntiFakeCode> list = antiFakeDao.findByNamedParams("from AntiFakeCode c where c.code=:code", new String[]{"code"}, code);
		if(list == null || list.size() < 1) {
			return null;
		}
		return list.get(0);
	}
	
	@Override
	public List<AntiFakeCode> apply(int count) {
		Query query = antiFakeDao.createQuery("from AntiFakeCode c where c.apply=?", false);
		query.setMaxResults(count);
		query.setFirstResult(0);
		List<AntiFakeCode> list = query.list();
		for(AntiFakeCode antiFakeCode : list) {
			antiFakeCode.setApply(true);
		}
		return list;
	}

	public IBaseDao<AntiFakeCode, Integer> getAntiFakeDao() {
		return antiFakeDao;
	}

	public void setAntiFakeDao(IBaseDao<AntiFakeCode, Integer> antiFakeDao) {
		this.antiFakeDao = antiFakeDao;
		this.antiFakeDao.setEntityClass(AntiFakeCode.class);
	}

	
}
